package com.GLM.Viewer.Friends;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.GLM.Constants.Constant;
import com.GLM.Entity.UserInfoDetailEntity;
import com.GLM.Tools.DB.DAO.UserInfoDAO;
import com.GLM.Tools.Utils.JSON.JSONResponse;
import com.GLM.Tools.Utils.JSON.JSONUtil;
import com.GLM.Tools.Utils.JSON.JSONResponse.Status;
import com.GLM.Viewer.R;
import com.GLM.Viewer.Users.UserInfoDetailActivity;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class FriendsGroupDetailActivity extends Activity{
	private final static int GROUP_LOADING = 111;
	private final static int GROUP_LONDED = 222;
	private ListView mGroupMemList;
	private SimpleAdapter mGroupsAdapter;
	private List<Map<String, Object>> mGroupItems = new ArrayList<Map<String, Object>>();
	private String[] groupItemKeys = new String[] { "memmsg","memnick","memloc","memmark" };
	private int[] groupItemIds = new int[] { R.id.group_item_msg,R.id.group_item_name,R.id.group_item_location,R.id.group_item_remark };
	private Map<Integer, Integer> groupsMap = new HashMap<Integer, Integer>();
	private int rgid;
	Button delButton;
	Button addButton;
	TextView groupNameView;
	int[] groupUserIds;
	private Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			Thread thread;
			
			switch (msg.what) {
			case GROUP_LOADING:
				mGroupItems.clear();
				groupsMap.clear();
				thread = new Thread(new Runnable() {
					public void run() {
						initGroupMembers(rgid);
						mGroupsAdapter = new SimpleAdapter(FriendsGroupDetailActivity.this, mGroupItems, R.layout.view_friends_groupitem_listitem,groupItemKeys, groupItemIds);
						mHandler.sendEmptyMessage(GROUP_LONDED);
					}

				});
				thread.start();
				break;
			case GROUP_LONDED:
				if(mGroupsAdapter != null){
					mGroupMemList.setAdapter(mGroupsAdapter);
					
					bindItemClick();
				}
				break;
			default:
				break;
			}
		};
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_friends_groupitem);
		mGroupMemList = (ListView)findViewById(R.id.friends_myfriends_list);
		initViews();
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		if(bundle != null){
			rgid = bundle.getInt("rg_id");
			String groupName = bundle.getString("groupName");
			groupNameView.setText(groupName);
		}
		mHandler.sendEmptyMessage(GROUP_LOADING);
	}

	public void initViews(){
		delButton = (Button)findViewById(R.id.friends_del_button);
		groupNameView = (TextView)findViewById(R.id.friends_group_name);
		addButton = (Button)findViewById(R.id.friends_add_btn);
		delButton.setOnClickListener(clickListeners);
		addButton.setOnClickListener(clickListeners);
	}
	
	public void bindItemClick(){
		mGroupMemList.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long id) {
				// TODO Auto-generated method stub
				int user_id = groupsMap.get(position);
				Intent intent = new Intent(FriendsGroupDetailActivity.this,UserInfoDetailActivity.class);
				intent.putExtra(Constant.INTENT_USER_ID, user_id);
				startActivity(intent);
			}
		});
	}
	
	
	public OnClickListener clickListeners = new OnClickListener() {
		
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.friends_del_button:
				int status = initDelGroup(rgid);
				if(status == 1){
					Intent intent = new Intent(FriendsGroupDetailActivity.this, FriendsGroupsActivity.class);
					startActivity(intent);
				}
				break;
			case R.id.friends_add_btn:
				Intent intent = new Intent(FriendsGroupDetailActivity.this,FriendsGroupMyFriendsActivity.class);
				intent.putExtra("friendIds", groupUserIds);
				intent.putExtra("rg_id", rgid);
				startActivityForResult(intent, Constant.FRIENDS_GROUPS_MODIFY);
				break;
			default:
				break;
			}
		}
	};
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode == RESULT_OK){
			switch (requestCode) {
			case Constant.FRIENDS_GROUPS_MODIFY:
				int status = data.getIntExtra("status", -1);
				if(status == 2){
					mHandler.sendEmptyMessage(GROUP_LOADING);
				}
				break;

			default:
				break;
			}
		}
		
	};
	
	public int initDelGroup(int groupid){
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		int status = -1;
		try {
			jsonData.put(Constant.PARAM_RGID, groupid);
			jsonData.put(Constant.PARAM_USERID, UserInfoDAO.getUserInfo(FriendsGroupDetailActivity.this).getUserId());
			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_DELETEFRIENDGROUP, jsonData);
			if(jsonResponse.getStatus() != Status.ERR){
				
				JSONObject data = jsonResponse.getData();
				status = data.getInt(Constant.RESP_STATUS);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return status;
	}
	
	
	public void initGroupMembers(int rg_id){
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		try {
			jsonData.put(Constant.PARAM_RGID, rg_id);
			jsonData.put(Constant.PARAM_USERID, UserInfoDAO.getUserInfo(FriendsGroupDetailActivity.this).getUserId());
			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_GETGROUPMEMBER , jsonData);
			if(jsonResponse.getStatus() != Status.ERR){
				int status = -1;
				JSONObject data = jsonResponse.getData();
				status = data.getInt(Constant.RESP_STATUS);
				if(status == Constant.RESP_STATUS_SUCCESS){
					JSONArray jsonArray = data.getJSONArray(Constant.RESP_GROUP_MEMBER);
					
					initMemsFromJSONObject(jsonArray);
				}
				
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	private void initMemsFromJSONObject(JSONArray jsonArray) throws JsonSyntaxException, JSONException {
		Gson gson = new Gson();
		int length = jsonArray.length();
		groupUserIds = new int[length];
		for (int i = 0; i < length; i++) {
			UserInfoDetailEntity entity = gson.fromJson(jsonArray.getJSONObject(i).toString(), UserInfoDetailEntity.class);
			Map<String, Object> item = new HashMap<String, Object>();
			
			item.put("memmsg", entity.getMsg()+"/"+entity.getFocus()+"/"+entity.getFollows());
			item.put("memnick", entity.getUd_nickname());
			item.put("memloc", entity.getLoc_name());
			String relName = entity.getUd_relname();
			if(relName == null || relName == ""){
				relName = getString(R.string.friends_myfriends_norelname);
			}
			item.put("memmark", relName);
			mGroupItems.add(item);
			groupsMap.put(i, entity.getUser_id());
			groupUserIds[i] = entity.getUser_id();
		}
		
	}
}
